package com.meituan.catering.management.shop.biz.service.impl;

import com.meituan.catering.management.common.model.biz.UserContextBO;
import com.meituan.catering.management.shop.api.http.model.request.CloseShopHttpRequest;
import com.meituan.catering.management.shop.api.http.model.request.CreateShopHttpRequest;
import com.meituan.catering.management.shop.api.http.model.request.OpenShopHttpRequest;
import com.meituan.catering.management.shop.api.http.model.request.UpdateShopHttpRequest;
import com.meituan.catering.management.shop.biz.model.ShopBO;
import com.meituan.catering.management.shop.biz.model.converter.ShopBOConverter;
import com.meituan.catering.management.shop.biz.model.converter.ShopDOConverter;
import com.meituan.catering.management.shop.biz.service.ShopBizOperateService;
import com.meituan.catering.management.shop.biz.service.ShopBizService;
import com.meituan.catering.management.shop.biz.service.ShopBusinessNoBizService;
import com.meituan.catering.management.shop.dao.mapper.ShopMapper;
import com.meituan.catering.management.shop.dao.model.ShopDO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;

/**
 * 操作服务
 */
@Service
public class ShopBizOperateServiceImpl implements ShopBizOperateService {
    @Resource
    ShopMapper shopMapper;

    @Resource
    ShopBusinessNoBizService shopBusinessNoBizService;

    @Resource
    ShopBizService shopBizService;

    @Resource
    TransactionTemplate transactionTemplate;

    public ShopBO createShop(UserContextBO userContext, CreateShopHttpRequest request) {
        ShopBO creatingShopBO = ShopBOConverter.fromHttpRequest(userContext, request);
        String businessNo = this.shopBusinessNoBizService.generate();
        creatingShopBO.setBusinessNo(businessNo);
        /*
         * 设置初始化版本
         */
        creatingShopBO.setVersion(1);
        ShopDO createdShopDO = this.transactionTemplate.execute((transactionStatus) -> {
            ShopDO shopDO = ShopDOConverter.fromBO(creatingShopBO);
            int insertRowCount = this.shopMapper.insert(shopDO);
            if (insertRowCount != 1) {
                transactionStatus.setRollbackOnly();
                throw new IllegalStateException("保存门店失败");
            } else {
                return this.shopMapper.findByBusinessNo(userContext.getTenantId(), businessNo);
            }
        });
        return ShopBOConverter.fromDO(createdShopDO);
    }

    @Override
    public ShopBO updateShop(UserContextBO userContextBO, String businessNo, UpdateShopHttpRequest request) {
        /*
         * 查找商户号是否存在
         */
        ShopBO existingShopBO = this.shopBizService.findByBusinessNo(userContextBO, businessNo);
        ShopBO updatingShopBO = ShopBOConverter.fromHttpRequest(userContextBO, existingShopBO, request);

        return this.doUpdateAndReloadShopInTransaction(userContextBO, businessNo, updatingShopBO);

    }

    public ShopBO open(UserContextBO userContext, String businessNo, OpenShopHttpRequest request) {
        ShopBO shopBO = this.shopBizService.findByBusinessNo(userContext, businessNo);
        /*
         * 如果从BO中为true  则抛出异常
         */
        if (shopBO.getEnabled()) {
            throw new IllegalStateException("该门店已启用");
        } else {
            ShopDO updatedShopDO = this.transactionTemplate.execute((transactionStatus) -> {
                int insertRowCount = this.shopMapper.changeEnabledById(userContext.getTenantId(), shopBO.getId(), 1, request.getVersion());
                if (insertRowCount != 1) {
                    transactionStatus.setRollbackOnly();
                    throw new IllegalStateException("启用门店失败");
                } else {
                    return this.shopMapper.findByBusinessNo(userContext.getTenantId(), businessNo);
                }
            });
            return ShopBOConverter.fromDO(updatedShopDO);
        }
    }

    public ShopBO close(UserContextBO userContext, String businessNo, CloseShopHttpRequest request) {
        ShopBO shopBO = this.shopBizService.findByBusinessNo(userContext, businessNo);
        if (!shopBO.getEnabled()) {
            throw new IllegalStateException("该门店已停用");
        } else {
            ShopDO updatedShopDO = this.transactionTemplate.execute((transactionStatus) -> {
                int insertRowCount = this.shopMapper.changeEnabledById(userContext.getTenantId(), shopBO.getId(),0, request.getVersion());
                if (insertRowCount != 1) {
                    transactionStatus.setRollbackOnly();
                    throw new IllegalStateException("停用门店失败");
                } else {
                    return this.shopMapper.findByBusinessNo(userContext.getTenantId(), businessNo);
                }
            });
            return ShopBOConverter.fromDO(updatedShopDO);
        }
    }


    /**
     * 保存门店方法
     * @param userContext 请求头信息（用户号，租户号）
     * @param businessNo 门店号
     * @param updatingShopBO ShopBO
     * @return ShopBO
     */
    private ShopBO doUpdateAndReloadShopInTransaction(UserContextBO userContext, String businessNo, ShopBO updatingShopBO) {
        ShopDO updatedShopDO = this.transactionTemplate.execute((transactionStatus) -> {
            ShopDO updatingShopDO = ShopDOConverter.fromBO(updatingShopBO);
            int insertRowCount = this.shopMapper.update(updatingShopDO);
            if (insertRowCount != 1) {
                transactionStatus.setRollbackOnly();
                throw new IllegalStateException("保存门店失败");
            } else {
                return this.shopMapper.findByBusinessNo(userContext.getTenantId(), businessNo);
            }
        });
        return ShopBOConverter.fromDO(updatedShopDO);
    }






}
